#!/usr/bin/python3
# -*- coding: utf-8 -*-

from flask import request, jsonify
from ..services.auth_service import AuthService
from ..services.user_service import UserService
from ..utils.api_response import ApiResponse
from ..utils.auth_utils import get_token_from_request

class AuthController:
    """认证控制器"""
    
    @staticmethod
    def register():
        """用户注册"""
        data = request.get_json()
        
        # 验证必要字段
        if not data or not data.get('username') or not data.get('password'):
            return ApiResponse.error("请提供用户名和密码", 400)
        
        # 创建用户
        try:
            user = AuthService.register_user(data)
            # 直接返回用户数据，不再嵌套在user字段下或提供message
            return ApiResponse.success(user)
        except ValueError as e:
            return ApiResponse.error(str(e), 400)
        except Exception as e:
            return ApiResponse.error(f"注册失败: {str(e)}", 500)
    
    @staticmethod
    def batch_register():
        """批量用户注册
        
        一次性注册多个用户，使用固定的账号密码格式，并返回所有成功注册的用户信息
        """
        data = request.get_json()
        
        # 验证必要字段
        if not data:
            return ApiResponse.error("请提供注册信息", 400)
        
        # 获取要注册的用户数量，默认100，最大500
        count = data.get('count', 100)
        if count <= 0:
            return ApiResponse.error("count 必须大于0", 400)
        if count > 500:
            return ApiResponse.error("一次最多创建500个用户", 400)
        
        # 获取密码，默认为 "password123"
        password = data.get('password', 'password123')
        
        try:
            # 批量创建用户
            success_count, error_count, users = UserService.batch_create_users(count, password)
            
            # 简化批量注册的响应结构
            return ApiResponse.success({
                "count": success_count,
                "failed": error_count,
                "users": users
            })
        except Exception as e:
            return ApiResponse.error(f"批量注册失败: {str(e)}", 500)
    
    @staticmethod
    def login():
        """用户登录"""
        data = request.get_json()
        
        # 验证必要字段
        if not data or not data.get('username') or not data.get('password'):
            return ApiResponse.error("请提供用户名和密码", 400)
        
        # 登录验证
        try:
            token, user = AuthService.login(data.get('username'), data.get('password'))
            
            # 将token与用户信息合并到同一层级
            response_data = {"token": token}
            # 将用户信息展开到顶层
            if isinstance(user, dict):
                response_data.update(user)
            
            return ApiResponse.success(response_data)
        except ValueError as e:
            return ApiResponse.error(str(e), 401)
        except Exception as e:
            return ApiResponse.error(f"登录失败: {str(e)}", 500)
    
    @staticmethod
    def userinfo():
        """获取用户信息，支持从请求头或查询参数获取token
        
        支持通过query参数设置:
        ?detail=basic - 仅返回基本信息
        ?detail=full - 返回所有用户信息(默认)
        ?extended=true - 包含扩展信息(roles、permissions等)
        """
        # 使用工具函数获取token
        token = get_token_from_request()
        
        if not token:
            return ApiResponse.error("缺少身份验证信息，请在请求头或查询参数中提供token", 401)
        
        # 验证token
        is_valid, user_info, message = AuthService.validate_user_token(token)
        if not is_valid:
            return ApiResponse.error(message, 401)
        
        # 获取详细程度参数
        detail_level = request.args.get('detail', 'full')
        include_extended = request.args.get('extended', '').lower() == 'true'
        
        # 如果只需要基本信息，直接返回token中包含的信息
        if detail_level == 'basic':
            return ApiResponse.success(user_info)
        
        # 获取完整用户信息
        try:
            user = UserService.get_user_by_id(user_info.get('user_id'), include_extended_info=include_extended)
            if not user:
                return ApiResponse.error("未找到用户信息", 404)
                
            # 确保用户对象转为字典（排除密码）
            user_data = user.to_dict(exclude_keys=['password']) if hasattr(user, 'to_dict') else user
            return ApiResponse.success(user_data)
        except Exception as e:
            return ApiResponse.error(f"获取用户信息失败: {str(e)}", 500)
        
    @staticmethod
    def mock_userinfo():
        """模拟用户信息，总是返回包含所有字段的完整用户数据
        支持通过query参数设置详细程度:
        ?fields=basic - 仅返回基本字段
        ?fields=full - 返回所有字段(默认)
        ?fields=custom&include=field1,field2,... - 返回自定义字段
        """
        try:
            # 获取字段选择参数
            fields_option = request.args.get('fields', 'full')
            include_fields = request.args.get('include', '')
            
            # 生成模拟用户数据
            user = UserService.generate_mock_user(detail_level=fields_option)
            
            # 如果是自定义字段，过滤结果
            if fields_option == 'custom' and include_fields:
                requested_fields = [field.strip() for field in include_fields.split(',')]
                user = {k: v for k, v in user.items() if k in requested_fields}
                
            return ApiResponse.success(user)
        except Exception as e:
            return ApiResponse.error(f"生成模拟用户信息失败: {str(e)}", 500)
    
    @staticmethod
    def admin_userinfo():
        """获取完整用户数据，无需鉴权（仅用于开发/测试环境）
        
        支持通过query参数设置详细程度:
        ?detail=basic - 仅返回基本字段
        ?detail=full - 返回所有字段(默认)
        ?fields=custom&include=field1,field2,... - 返回自定义字段
        
        可以通过user_id参数指定要返回的用户，例如：?user_id=123
        如果不指定，则返回模拟用户数据
        """
        try:
            # 获取detail参数
            detail_level = request.args.get('detail', 'full')
            
            # 获取user_id参数，如果有则获取特定用户，否则返回模拟用户
            user_id = request.args.get('user_id')
            
            if user_id:
                # 获取特定用户信息
                user = UserService.get_user_by_id(user_id, include_extended_info=True)
                if not user:
                    return ApiResponse.error(f"用户ID {user_id} 不存在", 404)
                    
                # 根据detail_level可以选择性返回部分字段
                if detail_level == 'basic':
                    basic_fields = ['id', 'user_id', 'username', 'email', 'name']
                    user = {k: v for k, v in user.items() if k in basic_fields}
            else:
                # 获取字段选择参数
                fields_option = request.args.get('fields', detail_level)
                include_fields = request.args.get('include', '')
                
                # 生成模拟用户数据
                user = UserService.generate_mock_user(detail_level=fields_option)
                
                # 如果是自定义字段，过滤结果
                if fields_option == 'custom' and include_fields:
                    requested_fields = [field.strip() for field in include_fields.split(',')]
                    user = {k: v for k, v in user.items() if k in requested_fields}
            
            # 返回结果
            return ApiResponse.success(user)
            
        except Exception as e:
            return ApiResponse.error(f"获取用户信息失败: {str(e)}", 500) 